<template>
  <div class="article-manager">
    <h2 class="title">个人文章管理</h2>
    <!-- 搜索和新建区域 -->
    <div class="toolbar">
      <input
          type="text"
          v-model="searchKeyword"
          placeholder="搜索文章..."
          class="search-input"
      >
      <div class="filter-wrapper">
      <select v-model="statusFilter" class="status-filter">
        <option value="">全部状态</option>
        <option
            v-for="(value, key) in statusOptions"
            :key="key"
            :value="key"
        >
          {{ value }}
        </option>
      </select>
      <button class="btn new-btn" @click="goTocreateArticle">新建文章</button>
    </div>
    </div>

    <!-- 文章表格 -->
    <div class="article-table-wrapper">
    <table class="article-table">
      <thead>
      <tr>
        <th><input type="checkbox" @change="toggleAllSelect" :checked="allSelected"></th>
        <th>标题</th>
        <th>标题图</th>
        <th>摘要</th>
        <th>分类</th>
        <th>标签</th>
        <th>状态</th>
        <th>创建时间</th>
        <th>操作</th>

      </tr>
      </thead>
      <tbody>
      <tr v-for="article in paginatedArticles" :key="article.id">
        <td data-label="选择"><input type="checkbox" v-model="selectedIds" :value="article.id"></td>
        <td data-label="标题">{{ article.title }}</td>
        <td data-label="标题图">
          <div class="thumbnail-wrapper">
            <template v-if="article.images && article.images.length > 1">
              <!-- 多图展示 -->
              <img
                  v-for="(image, index) in article.images.slice(0, 4)" :key="index"
                  :src="image.image"
                  class="article-thumbnail multiple"
                  @error="handleImageError"
                  :alt="'文章缩略图 ' + (index + 1)"
              >
            </template>
            <template v-else-if="article.image">
              <!-- 单图展示 -->
              <img
                  :src="article.image"
                  class="article-thumbnail single"
                  @error="handleImageError"
                  alt="文章缩略图"
              >
            </template>
            <template v-else>
              <!-- 无图展示 -->
              <span class="no-thumbnail">暂无标题图</span>
            </template>
          </div>
        </td>

        <td data-label="摘要" class="content-cell" v-html="article.excerpt"></td>
        <td data-label="分类">{{ article.category.name }}</td>
        <td data-label="标签">
          <template v-for="tag in article.tags"><span class="tag" :style="{'background-color': tag.color}">{{
              tag.name
            }}</span></template>
        </td>
        <td data-label="状态">{{ statusOptions[article.status] }}</td>
        <td data-label="创建时间">{{ article.created_date }}</td>
        <td data-label="操作">
          <button class="btn show-btn" @click="goToshowArticle(article.id)">查看</button>
          <button class="btn edit-btn" @click="goToeditArticle(article.id)">编辑</button>
          <button @click="deleteArticle(article.id)" class="btn delete-btn">删除</button>
        </td>
      </tr>
      </tbody>
    </table>
    </div>
    <!-- 在分页部分添加跳转输入 -->
    <div class="pagination">
      <button
          @click="currentPage--"
          :disabled="currentPage === 1"
          class="btn"
      >上一页
      </button>

      <span>第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>

      <button
          @click="currentPage++"
          :disabled="currentPage >= totalPages"
          class="btn"
      >下一页
      </button>

      <!-- 新增跳转输入 -->
      <div class="page-jump">
        <span>第</span>
        <input
            type="number"
            v-model.number="jumpPage"
            min="1"
            :max="totalPages"
            @keyup.enter="handleJump"
            placeholder="-"
        ><span>页</span>
        <button
            @click="handleJump"
            class="btn"
            :disabled="!jumpPageValid"
        >跳转
        </button>
      </div>
      <!-- 新增分页大小选择 -->
      <div class="page-size">
        <select v-model.number="itemsPerPage" @change="currentPage = 1">
          <option value="10">10条/页</option>
          <option value="15">15条/页</option>
          <option value="20">20条/页</option>
          <option value="50">50条/页</option>
          <option value="100">100条/页</option>
        </select>
      </div>
    </div>


    <!-- 批量删除 -->
    <!-- 在批量操作区域添加 -->
    <div class="batch-actions" v-if="selectedIds.length">
  <button
    @click="batchDelete"
    class="btn delete-btn"
    :disabled="deleting"
  >
    {{ deleting ? '删除中...' : `删除选中项 (${selectedIds.length})` }}
  </button>
  <span v-if="hasPublishedArticles" class="batch-warning">
    （包含已发布文章）
  </span>
</div>


  </div>

</template>

<script setup>
const router = useRouter()
// 模拟初始数据
const articles = ref([])
// 新增文章加载状态
const loading = ref(false)
const searchKeyword = ref('')
const selectedIds = ref([])
const deleting = ref(false)
// 新增分页相关变量
const currentPage = ref(1)
const itemsPerPage = ref(10)
const jumpPage = ref('')
// 新增状态相关数据
const statusFilter = ref('')
const statusOptions = ref({
  published: '已发布',
  draft: '草稿',
  pending: '待审核',
  rejected: '已驳回'
})


// 新增获取文章方法
const fetchArticles = async () => {
  try {
    loading.value = true
    const response = await axios.get('/api/cms/articles/get_my_articles/', {requiresAuth: true})
    const data = await response.data
    articles.value = data

    loading.value = false
  } catch (error) {
    console.error('获取文章失败:', error)
    loading.value = false
  }
}
// 在组件挂载时获取数据
onMounted(() => {
  fetchArticles()
})


// 监听搜索关键词变化时重置页码
watch(searchKeyword, () => {
  currentPage.value = 1
})

// 监听状态过滤器变化时重置页码
watch(statusFilter, () => {
  currentPage.value = 1
})

// 添加跳转验证
const jumpPageValid = computed(() => {
  return Number.isInteger(jumpPage.value) &&
      jumpPage.value > 0 &&
      jumpPage.value <= totalPages.value
})

// 添加跳转处理方法
const handleJump = () => {
  if (!jumpPageValid.value) {
    currentPage.value = 1
  } else {
    currentPage.value = Math.max(1, Math.min(jumpPage.value, totalPages.value))
  }
  jumpPage.value = ''
}
// 计算属性
// 修改过滤逻辑
const filteredArticles = computed(() => {
  return articles.value.filter(article => {
    const matchKeyword = article.title.includes(searchKeyword.value) ||
        article.excerpt.includes(searchKeyword.value)
    const matchStatus = statusFilter.value ?
        article.status === statusFilter.value : true
    return matchKeyword && matchStatus
  })
})


// 新增分页数据计算
const paginatedArticles = computed(() => {
  const start = (currentPage.value - 1) * itemsPerPage.value
  const end = start + itemsPerPage.value
  return filteredArticles.value.slice(start, end)
})

// 新增总页数计算
const totalPages = computed(() => {
  return Math.ceil(filteredArticles.value.length / itemsPerPage.value)
})

// 修改全选逻辑使用分页数据
const allSelected = computed(() => {
  return paginatedArticles.value.length > 0 &&
      paginatedArticles.value.every(a => selectedIds.value.includes(a.id))
})

// 方法
const toggleAllSelect = (e) => {
  if (e.target.checked) {
    selectedIds.value = filteredArticles.value.map(a => a.id)
  } else {
    selectedIds.value = []
  }
}


const deleteArticle = async (id) => {
  if (confirm('确定删除吗？')) {
    try {
      // 这里可以添加实际的删除接口调用
      await axios.delete(`/api/cms/articles/${id}/delete_article/`, {requiresAuth: true})
      const index = articles.value.findIndex(a => a.id === id)
      articles.value.splice(index, 1)
    } catch (error) {
      console.error('删除失败:', error)
    }
  }
}

const handleImageError = (e) => {
  e.target.src = 'https://picsum.photos/150/150?random=1'
}
const hasPublishedArticles = computed(() => {
  return selectedIds.value.some(id => {
    const article = articles.value.find(a => a.id === id)
    return article?.status === 'published'
  })
})

const batchDelete = async () => {
  if (deleting.value) return
  deleting.value = true
  if (!selectedIds.value.length) return

  if (hasPublishedArticles.value) {
    if (!confirm('包含已发布文章，确定要删除吗？')) return
  } else {
    if (!confirm(`确定删除选中的 ${selectedIds.value.length} 项吗？`)) return
  }
  try {
    // 调用批量删除接口
    await axios.post('/api/cms/articles/batch_delete_articles/', {
      article_ids: selectedIds.value
    }, {requiresAuth: true})

    // 过滤出保留的文章（更安全的做法）
    articles.value = articles.value.filter(
        article => !selectedIds.value.includes(article.id)
    )

    // 清空选中项
    selectedIds.value = []

    // 重置页码到第一页
    currentPage.value = 1

  } catch (error) {
    console.error('批量删除失败:', error)
    alert('删除操作失败，请稍后重试')
  } finally {
    deleting.value = false
  }
}

const goTocreateArticle = () => {
  // 这里可以添加实际的新建文章页面跳转
  router.push({'name': 'create-article'})
}
const goToshowArticle = (id) => {
  // 这里可以添加实际的文章详情页面跳转
  router.push({'name': 'show-article', params: {id}})
}
const goToeditArticle = (id) => {
  // 这里可以添加实际的编辑文章页面跳转
  router.push({'name': 'edit-article', params: {id}})
}


</script>

<style scoped>
/* 整体布局改动 */
.article-manager {
  max-width: 1200px;
  margin: 25px auto;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.title {
  font-size: 24px;
  font-weight: bold;
  align-items: center;
  justify-content: center;
  display: flex;
  margin-bottom: 20px;
  color: #4a5568;
}

/* 搜索工具栏优化 */
.toolbar {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
  align-items: center;
}
.filter-wrapper {
  display: flex;
  gap: 16px;
  align-items: center;
}
.status-filter {
  padding: 8px 12px;
  border: 1px solid #ccc;
  border-radius: 6px;
  background-color: white;
  transition: border-color 0.3s ease;
}

.status-filter:focus {
  outline: none;
  border-color: #4299e1;
  box-shadow: 0 0 3px rgba(66, 153, 225, 0.3);
}

.search-input {
  padding: 8px 4px;
  max-width: 300px;
  min-width: 250px;
  border: 1px solid #ccc;
  border-radius: 6px;
  transition: box-shadow 0.3s ease;
}

.search-input:focus {
  outline: none;
  box-shadow: 0 0 5px rgba(66, 139, 202, 0.5);
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  background-color: #f0f4f8;
  color: #4a5568;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.new-btn {
  background-color: #4299e1;
  color: white;
  transition: background-color 0.3s ease;
}

.new-btn:hover {
  background-color: #3182ce;
}

/* 表格优化 */
.article-table-wrapper {
  overflow-x: auto;
  -webkit-overflow-scrolling: touch; /* 提高移动端性能 */
}

.article-table {
  min-width: 768px; /* 设置表格最小宽度 */
  width: 100%; /* 保证全屏宽度 */
}


.article-table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 20px;
  background-color: white;
  overflow: hidden;
}

.article-table th, .article-table td {
  border: 1px solid #ccc;
  padding: 12px;
  text-align: left;
}

.article-table th {
  background-color: #f0f4f8;
  color: #4a5568;
}

.article-table tr:nth-child(even) {
  background-color: #f9f9f9;
}

.content-cell {
  max-width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.thumbnail-wrapper {
  width: 100px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.article-thumbnail {
  max-width: 100%;
  max-height: 100%;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  object-fit: cover;
}

.thumbnail-wrapper img.multiple {
  max-width: 48px;
  max-height: 30px;
  margin-right: 4px;
}

.thumbnail-wrapper img.single {
  max-width: 100%;
  max-height: 100%;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  object-fit: cover;
}

.no-thumbnail {
  color: #999;
  font-size: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100px;
  height: 60px;
}
.tag {
  display: inline-block;
  padding: 4px 8px;
  border-radius: 4px;
  margin-right: 4px;
  font-size: 0.8em;
  color: white;
  background-color: #4299e1;
}

/* 新增表单布局 */
.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 16px;
}

.preview-image {
  margin-top: 10px;

  img {
    max-width: 200px;
    max-height: 150px;
    border-radius: 4px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }
}


/* 优化“编辑”和“删除”按钮 */
.show-btn {
  background-color: #5FB878;
  color: white;
  transition: background-color 0.3s ease;
}

.show-btn:hover {
  background-color: #4aa06c;
}

.edit-btn {
  background-color: #4299e1;
  color: white;
  margin-left: 8px;
  transition: background-color 0.3s ease;
}

.edit-btn:hover {
  background-color: #3182ce;
}

.delete-btn {
  background-color: #e53e3e;
  color: white;
  transition: background-color 0.3s ease;
  cursor: pointer;
  margin-left: 8px;
}

.delete-btn:hover {
  background-color: #c53030;

}

/* 批量删除区域 */
.batch-actions {
  width: 300px;

  padding: 10px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  z-index: 10;
  flex-wrap: wrap;
  gap: 8px; /* 按钮间距 */
}

.batch-actions .btn {
  flex: 1 1 auto; /* 按钮自适应宽度 */
  padding: 6px 12px;
}

.batch-warning {
  font-size: 12px;
  color: #e53e3e;
  margin-left: 10px;
}


.delete-btn:disabled {
  background-color: #fed7d7;
  color: #c53030;
  cursor: not-allowed;
}

/* 新增分页样式 */
.pagination {
  margin: 20px 0;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 10px;
  justify-content: center;
}

.pagination .btn {
  padding: 6px 12px;
  background-color: #4299e1;
  color: white;
}

.pagination .btn:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.pagination span {
  color: #666;
  font-size: 0.9em;
}

/* 在分页样式中添加 */
.page-jump {
  display: flex;
  gap: 8px;
  margin-left: 15px;
}

.page-jump span {
  color: #666;
  font-size: 0.9em;
  align-items: center;
  justify-content: center;
  display: flex;
}

.page-jump input {
  width: 60px;
  padding: 6px;
  border: 1px solid #ccc;
  border-radius: 4px;
  text-align: center;
}

.page-jump input:focus {
  outline: none;
  border-color: #4299e1;
}

.page-size select {
  padding: 6px 12px;
  border: 1px solid #ccc;
  border-radius: 4px;
  margin-left: 15px;
  background-color: white;
  transition: border-color 0.3s ease;
}

.page-size select:focus {
  outline: none;
  border-color: #4299e1;
  box-shadow: 0 0 3px rgba(66, 153, 225, 0.3);
}


@media screen and (max-width: 768px) {
  .toolbar {
    flex-direction: column;
    }
  .search-input {
    max-width: 100%;
    min-width: 100%;
    margin-bottom: 10px;
  }
  .content-cell {
    max-width: 150px; /* 限制内容单元格宽度 */
  }

  .article-table th, .article-table td {
    font-size: 0.85em; /* 缩小字体 */
    padding: 8px; /* 减小单元格内边距 */
  }

  .btn {
    padding: 6px 10px; /* 缩小按钮样式 */
    font-size: 12px;
  }
  .pagination {
    gap: 8px; /* 减小分页间距 */
  }
  .page-jump input {
    width: 40px; /* 减小页码输入框宽度 */
  }
  .page-size select {
    margin-left: 10px; /* 减小页码选择器左边距 */
  }
  .batch-actions {
    flex-wrap: wrap;
    gap: 6px;
    padding: 10px;
    margin:0 auto;
    justify-content: space-between;
  }

}

</style>


